import { NextResponse } from 'next/server';
import { getLocationUrl } from './header';
import { permanentRedirect } from 'next/navigation';

export function redirectToLogin(returnUrl?: string) {
  const backUrl = getLocationUrl(returnUrl);
  const oUrl = new URL(backUrl);
  const origin = oUrl.origin;
  const url =
    process.env.NEXT_PUBLIC_LOGIN_URL +
    '?return_url=' +
    encodeURIComponent(origin + '/api/login?backurl=' + backUrl);
  return NextResponse.redirect(url);
}

export function redirectToNoHtml(
  base: string,
  slug: string[] = [],
  query = {}
) {
  let isRedirect = false;
  if (!slug.length) return isRedirect;

  // if ends with .html
  if (slug[slug.length - 1].endsWith('.html')) {
    const queryStr = new URLSearchParams(query).toString();
    const qstr = queryStr ? '?' + queryStr : '';
    const url = base + '/' + slug.join('/').replace(/\.html$/, '') + qstr;
    isRedirect = true;
    permanentRedirect(url);
  }

  return isRedirect;
}
